package codegenerator;

import java.util.List;
import java.util.Properties;

import org.beetl.sql.core.ClasspathLoader;
import org.beetl.sql.core.ConnectionSource;
import org.beetl.sql.core.ConnectionSourceHelper;
import org.beetl.sql.core.Interceptor;
import org.beetl.sql.core.SQLLoader;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.db.DBStyle;
import org.beetl.sql.core.db.MySqlStyle;
import org.beetl.sql.core.db.TableDesc;
import org.beetl.sql.ext.DebugInterceptor;
import org.beetl.sql.ext.gen.GenConfig;
import org.beetl.sql.ext.gen.MapperCodeGen;

/**
 * 
 * @author Lay
 *
 */
public class CodeGeneratorUtil {

	public static SQLManager createSQLManager() throws Exception {
		Properties p = new Properties();
		p.load(CodeGeneratorUtil.class
				.getResourceAsStream("/application.properties"));
		String driver = p.getProperty("spring.datasource.driver-class-name");
		String url = p.getProperty("spring.datasource.url");
		String userName = p.getProperty("spring.datasource.username");
		String password = p.getProperty("spring.datasource.password");
		ConnectionSource source = ConnectionSourceHelper.getSimple(driver, url,
				userName, password);
		DBStyle mysql = new MySqlStyle();
		SQLLoader loader = new ClasspathLoader("/sql");
		CustomNameConversion nc = new CustomNameConversion();
		SQLManager sqlManager = new SQLManager(mysql, loader, source, nc,
				new Interceptor[] { new DebugInterceptor() });
		return sqlManager;
	}

	public static GenConfig createGenConfig(String basePackage) {
		GenConfig config = new GenConfig();
		config.preferBigDecimal(true);
		MapperCodeGen mapper = new MapperCodeGen(basePackage + ".mapper");
		config.codeGens.add(mapper);
		return config;

	}

	public static void generate(String table, String basePackage)
			throws Exception {
		SQLManager sqlManager = createSQLManager();
		GenConfig config = createGenConfig(basePackage);
		sqlManager.genPojoCode(table, basePackage + ".model", config);
	}

	public static void generate(List<String> tables, String basePackage)
			throws Exception {
		SQLManager sqlManager = createSQLManager();
		GenConfig config = createGenConfig(basePackage);
		String pojoPackage = basePackage + ".model";
		for (String table : tables) {
			TableDesc td = sqlManager.getMetaDataManager().getTable(table);
			String tableName = td.getName();
			String className = sqlManager.getNc().getClassName(tableName);
			className = pojoPackage + "." + className;
			try {
				Class.forName(className);
			} catch (ClassNotFoundException e) {
				sqlManager.genPojoCode(table, pojoPackage, config);
			}
		}
	}
}
